package com.sankuai.inf.leaf.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author final
 * @description
 * @date 2019-07-16 13:35
 */

@Configuration
public class LocalMvcConfiguration implements WebMvcConfigurer {
    public final static String SESSION_KEY = "username";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截登录
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //拦截的配置
        addInterceptor.addPathPatterns("/static/views/index.html","/api/**");
        //不拦截的配置
        addInterceptor.excludePathPatterns("/static/views/user/login.htm","/api/segment/**","/api/snowflake/**");

    }

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }


    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
            HttpSession session = request.getSession();
//            判断是否已有该用户登录的session
            if (session.getAttribute(SESSION_KEY) != null) {
                return true;
            }
//            跳转到登录页
            String url = "/static/views/user/login.html";
            response.sendRedirect(url);
            return false;
        }
    }
}


